/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlinganhang.view;

import java.awt.Color;
import java.sql.SQLException;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumnModel;
import org.jdesktop.swingx.JXTableHeader;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import quanlinganhang.dao.AccountTypeDAO;
import quanlinganhang.dao.LoginDAO;
import quanlinganhang.model.AccountTypeTableModel;

/**
 *
 * @author SIPO
 */
public class AccountType extends javax.swing.JPanel {

    /**
     * Creates new form AccountType
     */
    public AccountType() {
        initComponents();
        loadAccountCategory();
    }

    /**
     * Reload table data
     */
    private void reloadTable() {
        try {
            tblAccountType.setModel(new AccountTypeTableModel());
            //cột Mã người dùng có màu và căn giữa
            tblAccountType.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
            //Cột  Mật khẩu đổi qua màu xanh
            tblAccountType.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());
        } catch (SQLException | ClassNotFoundException ex) {
            new CustomMessageDialog(null, true, "Lỗi cơ sở dữ liệu",
                    "Có lỗi trong quá trình lấy thông tin dữ liệu", CustomMessageDialog.MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblAccountType = new org.jdesktop.swingx.JXTable();
        btAdd = new javax.swing.JButton();
        btEdit = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        btUpdate = new javax.swing.JButton();

        tblAccountType.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblAccountType);

        jTabbedPane1.addTab("Các loại tài khoản", jScrollPane1);

        btAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/add.png"))); // NOI18N
        btAdd.setText("Thêm");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });

        btEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/edit.png"))); // NOI18N
        btEdit.setText("Sửa");
        btEdit.setEnabled(false);
        btEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditActionPerformed(evt);
            }
        });

        btDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/delete.png"))); // NOI18N
        btDelete.setText("Xóa");
        btDelete.setEnabled(false);
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });

        btUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/refresh.png"))); // NOI18N
        btUpdate.setText("Cập nhật");
        btUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btUpdateActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 686, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(90, 90, 90)
                        .addComponent(btAdd)
                        .addGap(51, 51, 51)
                        .addComponent(btEdit)
                        .addGap(58, 58, 58)
                        .addComponent(btDelete)
                        .addGap(61, 61, 61)
                        .addComponent(btUpdate)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAdd)
                    .addComponent(btEdit)
                    .addComponent(btDelete)
                    .addComponent(btUpdate))
                .addContainerGap(26, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        new AddAccountType(LoginDAO.frmMain, true);
        reloadTable();
	}//GEN-LAST:event_btAddActionPerformed

    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteActionPerformed
        // TODO add your handling code here:
        int t = JOptionPane.showConfirmDialog(null, "Bạn có chắc chắn muốn xóa loại tài"
                + " khoản này", "Xác nhận", JOptionPane.YES_OPTION);
        if (t == JOptionPane.YES_OPTION) {
            int selected = tblAccountType.getSelectedRow();
            long id = Long.parseLong(tblAccountType.getValueAt(selected, 0).toString());
            try {
                if (AccountTypeDAO.DeleteAccountType(id)) {
                    new CustomMessageDialog(null, true, "Thành công",
                            "Xóa loại tài khoản thành công!", CustomMessageDialog.MESSAGE);
                    reloadTable();
                }
            } catch (ClassNotFoundException | SQLException ex) {
                new CustomMessageDialog(null, true, "Lỗi cơ sở dữ liệu",
                        "Có lỗi trong quá trình xóa loại tài khoản ", CustomMessageDialog.MESSAGE);
            }
        }
    }//GEN-LAST:event_btDeleteActionPerformed

    private void btUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btUpdateActionPerformed
        // TODO add your handling code here:
        reloadTable();
    }//GEN-LAST:event_btUpdateActionPerformed

    private void btEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditActionPerformed
        // TODO add your handling code here:
        int selected = tblAccountType.getSelectedRow();
        long id = Long.parseLong(tblAccountType.getValueAt(selected, 0).toString());
        String name = tblAccountType.getValueAt(selected, 1).toString();
        float interest = Float.parseFloat(tblAccountType.getValueAt(selected, 2).toString());
        int deadline = Integer.parseInt(tblAccountType.getValueAt(selected, 3).toString());
        String note = tblAccountType.getValueAt(selected, 4).toString();
        new AddAccountType(LoginDAO.frmMain, true, id, name, interest, deadline, note);
        reloadTable();
    }//GEN-LAST:event_btEditActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btDelete;
    private javax.swing.JButton btEdit;
    private javax.swing.JButton btUpdate;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private org.jdesktop.swingx.JXTable tblAccountType;
    // End of variables declaration//GEN-END:variables

    private void loadAccountCategory() {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        try {
            tblAccountType.setModel(new AccountTypeTableModel());

            tblAccountType.setHighlighters(HighlighterFactory.createSimpleStriping());

            tblAccountType.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            //set màu sắc của row khi cuộn qua (màu background của row và màu text của row)
            tblAccountType.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                    null, new Color(255, 102, 0)));
            //if did not choose 1 row, button Sửa and Xóa will be disable
            tblAccountType.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (tblAccountType.getSelectedRow() != -1) {
                        btEdit.setEnabled(true);
                        btDelete.setEnabled(true);
                    } else {
                        btEdit.setEnabled(false);
                        btDelete.setEnabled(false);
                    }
                }
            });

            TableColumnModel columnModel = tblAccountType.getColumnModel();
            tblAccountType.setTableHeader(new JXTableHeader(columnModel) {
                @Override
                public void updateUI() {
                    super.updateUI();
                    // need to do in updateUI to survive toggling of LAF 
                    if (getDefaultRenderer() instanceof JLabel) {
                        ((JLabel) getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
                    }
                }
            });
            tblAccountType.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
            tblAccountType.getColumn(1).setCellRenderer(new MyTableRenderer.ColorRenderer());
        } catch (SQLException | ClassNotFoundException ex) {
            new CustomMessageDialog(null, true, "Lỗi cơ sở dữ liệu",
                    "Có lỗi trong quá trình lấy thông tin dữ liệu", CustomMessageDialog.MESSAGE);
        }
    }
}
